import { NestFactory } from '@nestjs/core'
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'
import { AppModule } from './app.module'
import { ResData, SimpleUser, User } from './model/result.dto'
import { UserDto } from './model/user.dto'
import { CustomErrorFilter } from './utils/custom-error.filter'

async function bootstrap() {
  const prefix = 'api'
  const prefixDoc = 'docs'
  const app = await NestFactory.create(AppModule)
  // 启动 CORS
  app.enableCors()
  // 设置全局前缀为 'api'
  app.setGlobalPrefix(prefix)
  app.useGlobalFilters(new CustomErrorFilter())

  const options = new DocumentBuilder()
    .setTitle('UNI FTEAM MOCK API 文档')
    .setDescription(
      // '描述：<a href="http://localhost:3000/api-json">默认 json 链接</a>',
      `描述：<a href="http://localhost:3000/${prefixDoc}-json">默认 json 链接</a>`,
    )
    .setVersion('1.0.0')
    .setOpenAPIVersion('3.1.0')
    // .addServer("http://localhost:9000", "开发环境")
    // .addServer("https://test.com/release", "正式环境")
    // 添加标签
    .setContact('Cooliean', 'https://www.fteam.cc', 'cooliean@qq.com')
    // token认证，输入token才可以访问文档 这里的配置项可以为空
    .addBearerAuth()
    .build()
  // 创建文档
  const document = SwaggerModule.createDocument(app, options, {
    deepScanRoutes: true,
    operationIdFactory: (
      controllerKey: string,
      methodKey: string,
    ) => methodKey,
    extraModels: [ResData, User, SimpleUser, UserDto],
  })
  // 设置文档路径 为 api
  SwaggerModule.setup(prefixDoc, app, document, {
    swaggerOptions: {
      persistAuthorization: true,
      docExpansion: 'none',
      filter: true,
      showExtensions: true,
      showCommonExtensions: true,
    },
  }) // 访问路径 http://localhost:3000/${prefixDoc}

  await app.listen(process.env.PORT ?? 3000, () => {
    console.log(`API 地址：http://localhost:${process.env.PORT ?? 3000}/${prefix}`)
    console.log(`swagger ui 地址：http://localhost:${process.env.PORT ?? 3000}/${prefixDoc}`)
    console.log(`swagger json 地址：http://localhost:${process.env.PORT ?? 3000}/${prefixDoc}-json`)
  })
}

(async function () {
  await bootstrap()
})()
